import { onMounted, ref } from 'vue';

/* 组件在第几帧去渲染(使用defer优化白屏时间)
  import { useDefer } from '@utils/useDefer.js'
  const defer = useDefer();

  <component-one v-if="defer(1)">
  <component-one v-if="defer(2)">
  <component-one v-if="defer(3)">
*/
export function useDefer(maxCount = 100) {
  const frameCount = ref(0);
  let rafId;
  function updateFrameCount() {
    rafId = requestAnimationFrame(() => {
      frameCount.value++;
      if (frameCount.value > maxCount) return;
      updateFrameCount();
    });
  }
  updateFrameCount();
  onMounted(() => {
    cancelAnimationFrame(rafId);
  });
  return function defer(n) {
    return frameCount.value >= n;
  };
}
